package com.lyc.kotlin.wanandroid.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.lyc.kotlin.wanandroid.constant.Constant
import com.lyc.kotlin.wanandroid.event.NetworkChangeEvent
import com.lyc.kotlin.wanandroid.utils.Preference
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 描述
 *liuyucheng
 * Created By 刘育成 on 2019/7/31.
 */
abstract class BaseFragment :Fragment() {
    /**
     * 缓存上一次的网络状态
     */
    protected var hasNetwork: Boolean by Preference(Constant.HAS_NETWORK_KEY, true)

    /**
     * 视图是否加载完毕
     */
    private var isViewPrepare = false
    /**
     * 数据是否加载过了
     */
    private var hasLoadData = false

    abstract fun attachLayoutRes(): Int
    /**
     * 懒加载
     */
    abstract fun lazyLoad()

    abstract fun initView(view: View)

    /**
     * 是否使用 EventBus
     */
    open fun useEventBus(): Boolean = true

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater?.inflate(attachLayoutRes(),null)
    }
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            lazyLoadDataIfPrepared()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (useEventBus()){
            EventBus.getDefault().register(this)
        }
        isViewPrepare=true
        initView(view)
        lazyLoadDataIfPrepared()
    }



    private fun lazyLoadDataIfPrepared() {
        if (userVisibleHint && isViewPrepare && !hasLoadData) {
            lazyLoad()
            hasLoadData = true
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetworkChangeEvent(event: NetworkChangeEvent) {
        if (event.isConnected) {
            doReConnected()
        }
    }

    private fun doReConnected() {
        lazyLoad()
    }

}